package cn.sumpu.app.guoguojie.biz.impl;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.sumpu.app.guoguojie.biz.MailBiz;
import cn.sumpu.app.guoguojie.domain.Member;
import cn.sumpu.app.guoguojie.exception.AppBusinessException;

public class MailBizImpl implements MailBiz {

	private String mailUsername;
	private String mailPassword;
	private String mailEmail;

	private Properties props;
	private BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(
			100);
	private ThreadPoolExecutor exec = new ThreadPoolExecutor(5, 10, 60,
			TimeUnit.SECONDS, queue);
	private final static Logger logger = LoggerFactory
			.getLogger(MailBizImpl.class);

	@SuppressWarnings("rawtypes")
	@Override
	public void sendEmail(final String basePath, final Member member)
			throws AppBusinessException {
		Future f = exec.submit(new Send(basePath, member));
		try {
			f.get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
	}

	class Send implements Runnable {

		private Member member;
		private String basePath;

		Send(String basePath, Member member) {
			this.member = member;
			this.basePath = basePath;
		}

		@Override
		public void run() {
			Session session = Session.getInstance(props,
					new SimpleAuthenticator());
			session.setDebug(true);
			MimeMessage msg = new MimeMessage(session);
			try {
				msg.setFrom(new InternetAddress(mailEmail, "善圃"));
				String toEmail = member.getEmail();
				InternetAddress[] address = { new InternetAddress(toEmail) };
				msg.setRecipients(Message.RecipientType.TO, address);
				msg.setSubject("善圃注册邮件");
				msg.setSentDate(new Date());
				//构造登录路径
				msg.setContent(member.getUsername()+"您好：<br /><br />"+
						"欢迎入驻果果街！<br />请点击下面的链接完成注册：<br />"+
						"<a href='"+basePath + "successValede.ajax?number="+member.getIdentifier()+"'>"+
						basePath + "successValede.htm?number="+member.getIdentifier()+"</a>"+
						"<br />如果以上链接无法点击，请将上面的地址复制到你的浏览器的地址输入框(如IE)的地址栏进行验证。<br /><br />"+
						"(这是一封自动产生的email，请勿回复。)<br />" +
						"--果果街", 
						"text/html ;charset=utf-8");
				Transport.send(msg);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();

				if (logger.isErrorEnabled()) {
					logger.error("send mail error.", e);
				}
			} catch (MessagingException e) {
				e.printStackTrace();
				if (logger.isErrorEnabled()) {
					logger.error("send mail error.", e);
				}
			}
		}
	}

	public String getMailUsername() {
		return mailUsername;
	}

	public void setMailUsername(String mailUsername) {
		this.mailUsername = mailUsername;
	}

	public String getMailPassword() {
		return mailPassword;
	}

	public void setMailPassword(String mailPassword) {
		this.mailPassword = mailPassword;
	}

	public String getMailEmail() {
		return mailEmail;
	}

	public void setMailEmail(String mailEmail) {
		this.mailEmail = mailEmail;
	}

	public Properties getProps() {
		return props;
	}

	public void setProps(Properties props) {
		this.props = props;
	}

	class SimpleAuthenticator extends Authenticator {

		@Override
		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(mailUsername, mailPassword);
		}

	}

}
